#include <stdio.h>
#include <string.h>

/* 二进制取反 */
int convert(unsigned * dst, const unsigned char * src, int length)
{
	int i;

	for (i = 0; i < length; i++) {
		dst[i] = src[i] ^ 0xFF;
	}

	return 0;
}

/*
 * 十六进制转为十进制
 *
 * 十六进制每个字符位所表示的十进制数的范围是0 ~255，进制为256	  左移8位(<<8)等价乘以256
 */
unsigned long hex_dec(const unsigned char * hex, int length)
{
	int i;
	unsigned long ret = 0;

	for (i = 0; i < length; i++) {
		ret += (unsigned int) ( hex[i] << ( 8 * ( length - 1 - i )));
	}

	return ret;
}

/* 十进制转十六进制	*/
int dec_hex(int dec, unsigned char * hex, int length)
{
	int i;

	for ( i = length - 1; i >= 0; i--) {
		hex[i] = ( dec % 256 ) & 0xFF;
		dec /= 256;
	}

	return 0;
}

/* 求权 */
unsigned long power(int base, int times)
{
	int i;
	unsigned long ret = 1;

	for ( i = 0; i < times; i++) {
		ret *= base;
	}

	return ret;
}

/*
 * BCD转10进制
 * 压缩BCD码一个字符所表示的十进制数据范围为0 ~ 99,进制为100, 先求每个字符所表示的十进制值，然后乘以权
 */
unsigned long bcd_dec(const unsigned char * bcd, int length)
{
	int i, temp;
	unsigned long dec = 0;

	for ( i = 0; i < length; i++) {
		temp = (( bcd[i] >> 4 ) & 0x0F) * 10 + ( bcd[i] & 0x0F);
		dec += temp * power(100, length - 1 - i);

		printf("bcd to dec = %d\n", dec);
	}

	return dec;
}

/*
 * 十进制转BCD码
 * unsigned char *bcd            转换后的BCD码
 */
int dec_bcd(int dec, unsigned char * bcd, int length)
{
	int i;
	int temp;

	for ( i = length - 1; i >= 0; i--) {
		temp = dec % 100;
		bcd[i] = (( temp / 10 ) << 4 ) + (( temp % 10 ) % 0x0F );
		dec /= 100;
	}

	return 0;
}

int to_bcd(int a)
{
	int ret = 0, sh = 0;

	while ( a > 0 ) {
		ret |= ( a % 10 ) << sh;
		a /= 10;
		sh += 4;
	}

	return ret;
}

int b_to_dec(int bcd)
{
    /* 15用BCD码表示为 0001 0101 */
    //int bcd = 0x15;
    int dec;
	
	printf("bcd to dec = %x\n", bcd);
    dec = (bcd & 15) + ((bcd>>4) * 10);

    return dec;
}

int _dec_hex(int dec, unsigned char * hex, int length)
{
	int i;

	for ( i = length - 1; i >= 0; i--) {
		hex[i] = ( dec % 256 ) & 0xFF;
		dec /= 256;
	}

	return 0;
}

#define HEC_DEC(value)	((unsigned int)(value))

int main()
{
	register int i;
	unsigned char buf[12] = "";
	unsigned char hex[4] = {0x34, 0xFE, 0x3E, 0xFF};
    unsigned long dec = 0;
	unsigned char h = 0x35;

	dec = HEC_DEC(0x36);
	printf("hex to dec = %d\n", dec);

	//BCD码转十进制
	/*unsigned long bcd = 0;
	unsigned char BCD[4] = {0x98, 0x23, 0x45, 0x78};

	dec = bcd_dec(BCD, 1);

	dec = to_bcd(17);
	printf("bcd to dec = %d\n", dec);

	dec = b_to_dec(16);
	printf("bcd to dec = %d\n", dec);*/

	return 0;
}
